<script setup lang="ts">
import { useUserStore } from '@/store/modules/user-store'
import { getLodop } from '@/lib/lodop/LodopFuncs'
import { ref , nextTick} from 'vue'
import dayjs from 'dayjs'
import printModal from '@/components/business/print-modal/index.vue'
import { outOrderApi } from '@/api/business/storage/outbound-api'

const open = ref<boolean>(false)
const emit = defineEmits(['close', 'getList'])
const userStore = useUserStore()

const visible = ref(false)
// 详情
const options = ref({})
const batchLog = ref([])
defineExpose({
  showDrawer
})
function showDrawer(item, detail) {
  options.value = {
    no: detail.related?.no ?? detail.related?.order_no,
    create_time: detail.create_time,
    order_amount: item.order_amount,
    printLog: detail.printLog,
    related_type: detail.related_type,
    remark: detail.remark,
    detail: detail.related?.detail.map((item) => {
      return {
        ...item,
        num: item?.num ?? item.quantity,
        goods_batch: item.goods_batch ? item.goods_batch.map((item) => item.batch_time)?.join(', ') : ''
      }
    }),
    id: detail.id
  }
  // 对 options.value 按照 item.goods_name 的首字母排序，数字开头的放后边按数字大小排序，忽略开头空格
  options.value.detail.sort((a, b) => {
    // 去除 goods_name 开头的空格
    const aTrimmedName = a.goods.goods_name.trimStart()
    const bTrimmedName = b.goods.goods_name.trimStart()

    const aFirstChar = aTrimmedName.charAt(0)
    const bFirstChar = bTrimmedName.charAt(0)
    const isADigit = !isNaN(Number(aFirstChar))
    const isBDigit = !isNaN(Number(bFirstChar))

    if (isADigit && !isBDigit) {
      return 1 // a 是数字开头，b 不是，a 排在 b 后面
    } else if (!isADigit && isBDigit) {
      return -1 // a 不是数字开头，b 是，a 排在 b 前面
    } else if (isADigit && isBDigit) {
      // 都是数字开头，只取首数字按大小排序
      const aNumber = Number(aFirstChar)
      const bNumber = Number(bFirstChar)
      return aNumber - bNumber
    } else {
      // 都不是数字开头，按首字母排序
      return aTrimmedName.localeCompare(bTrimmedName)
    }
  })
  batchLog.value = detail.batchLog
  visible.value = true
}
function onClose() {
  visible.value = false
}

const loading = ref(false)
const printLoading = ref(false)
const usePrint = () => {

const onPrint = async () => {
  printLoading.value = true

  try {
    const valData = await outOrderApi.detail({ id: options.value.id, is_print: true })
    options.value.printLog = valData.data.printLog 
  } catch (error) {
    console.error('更新打印次数失败', error)
    printLoading.value = false
    return
  }

  await nextTick()

  const LODOP = getLodop()
  if (!LODOP) {
    open.value = true
    printLoading.value = false
    return
  }

  LODOP.PRINT_INITA('0mm', '0mm', '241mm', '93mm', '出库单')
  LODOP.SET_PRINT_PAGESIZE(1, '215.9mm', '93mm', '出库单')
  const printHTML = document.querySelector('#printSalesOutbound')?.outerHTML
  LODOP.ADD_PRINT_TABLE(20, '3%', '94%', '100%', printHTML)
  LODOP.SET_PRINT_STYLEA(0, 'TableRowThickNess', '12pt')
  LODOP.ADD_PRINT_TEXT(30, '3%', 196, 20, '县链云仓')
  LODOP.SET_PRINT_STYLEA(0, 'ItemType', 0)
  LODOP.NewPageA()
  LODOP.PREVIEW()
  printLoading.value = false
}
  return {
    onPrint
  }
}
const { onPrint } = usePrint()
function handleModalClose() {
  open.value = false
}
</script>

<template>
  <printModal :open="open" @cancel="handleModalClose" />
  <a-drawer title="出库单打印" :open="visible" @close="onClose">
    <template #closeIcon>
      <close @on-close="onClose" />
    </template>
    <table id="printSalesOutbound" border="0" center cellSpacing="0" cellPadding="1" width="100%" style="border-collapse: collapse; font-size: 11pt">
      <tbody>
        <tr>
     <td colspan="8">
            <div style="line-height: 30px; text-align: center; font-size: 16pt; font-weight: 700">{{ userStore.getCompanyInfo.name }}出库单</div>
            <font style="position: absolute; right: 0; top: 0">
              <span tdata="pageNO" format="#">#</span>
              <span>/</span>
              <span tdata="pageCount" format="#">##</span>
            </font>
          </td>
  </tr>
        </tbody>
      <tbody v-loading="loading">
        <tr>
          <td colspan="8">单据日期: {{ options?.create_time }}&nbsp;&nbsp;&nbsp;&nbsp;源订单编号: {{ options?.no }}</td>
        </tr>
        <tr>
          <td colspan="8"> 金额: {{ Number(options?.order_amount).toFixed(2) }} &nbsp;&nbsp;&nbsp;&nbsp;打印次数: {{ options?.printLog?.print_count || 0 }}&nbsp;&nbsp;&nbsp;&nbsp;打印时间: {{ dayjs().format('YYYY-MM-DD HH:mm:ss') }}</td>
        </tr>
        <tr>
          <td width="10%" style="border: 1pt solid #000">
            <div align="center"><b>序号</b></div>
          </td>
          <td width="30%" style="border: 1pt solid #000">
            <div align="center"><b>商品名称</b></div>
          </td>
          <td width="7%" style="border: 1pt solid #000">
            <div align="center"><b>单位</b></div>
          </td>
          <td width="20%" style="border: 1pt solid #000" v-if="options.related_type !== 'PurchaseOrder'">
            <div align="center"><b>销售价</b></div>
          </td>
          <td width="10%" style="border: 1pt solid #000">
            <div align="center"><b>数量</b></div>
          </td>
          <td width="10%" style="border: 1pt solid #000">
            <div align="center"><b>生产日期</b></div>
          </td>
          <td width="7%" style="border: 1pt solid #000">
            <div align="center"><b>保质期</b></div>
          </td>
          <td width="10%" style="border: 1pt solid #000">
            <div align="center"><b>备注</b></div>
          </td>
        </tr>
        <tr v-for="(item, index) in options?.detail" :key="item.id">
          <td style="border: 1pt solid #000; text-align: center">{{ index + 1 }}</td>
          <td style="border: 1pt solid #000; text-align: center">{{ item.goods.goods_name || '-' }}</td>
          <td style="border: 1pt solid #000; text-align: center">{{ item.spec.unit_name || '-' }}</td>
          <td style="border: 1pt solid #000; text-align: center" v-if="options.related_type !== 'PurchaseOrder'">{{ item.real_price ?? item.price }}</td>
          <td style="border: 1pt solid #000; text-align: center">
            {{ item.num }}
          </td>
          <td style="border: 1pt solid #000; text-align: center">{{ item?.goods_batch }}</td>
          <td style="border: 1pt solid #000; text-align: center">{{ item?.goods?.shelf_life_day || '' }}天</td>
          <td style="border: 1pt solid #000; text-align: center">{{ item.remark }}</td>
        </tr>
        <tr>
          <td style="border: 1pt solid #000; text-align: center">总计</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
          <td style="border: 1pt solid #000" v-if="options.related_type !== 'PurchaseOrder'">&nbsp;</td>
          <td style="border: 1pt solid #000; text-align: center">
            <span>{{ options?.detail.reduce((prev, item) => prev + Number(item.num), 0) || '-' }}</span></td
          >
          <td style="border: 1pt solid #000">&nbsp;</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
        </tr>
        <tr>
          <td colspan="3" style="font-weight: bold">备注: {{ options?.remark }}</td>
        </tr>
        <tr>
          <td colspan="3">仓管签字：</td>
          <td colspan="2">出库人签字：</td>
        </tr>
      </tbody>
    </table>
    <template #footer>
      <div class="flex justify-end">
        <a-button type="default" @click="onClose" style="margin-right: 8px">关闭</a-button>
        <a-button :loading="printLoading" type="primary" @click="onPrint">打印</a-button>
      </div>
    </template>
  </a-drawer>
</template>
